import {
	createStore
} from 'vuex';
import storage from '@/utils/storage.js';
import {
	authApi,
	categoryApi,
	recordApi,
	userApi
} from '@/api/index.js';

const store = createStore({
	state: {
		accessToken: storage.getAccessToken() || '',
		refreshToken: storage.getRefreshToken() || '',
		userInfo: storage.getUserInfo() || null,
		categoryTree: [],
		categories: [],
		records: [],
		loading: {
			user: false,
			categories: false,
			records: false
		}
	},

	mutations: {
		SET_ACCESS_TOKEN(state, tokenData) {
			state.accessToken = tokenData.accessToken;
			storage.setAccessToken(tokenData);
		},

		SET_REFRESH_TOKEN(state, token) {
			state.refreshToken = token;
			storage.setRefreshToken(token);
		},

		SET_USER_INFO(state, userInfo) {
			state.userInfo = userInfo;
			storage.setUserInfo(userInfo);
		},

		SET_CATEGORIES(state, categories) {
			state.categories = categories;
		},
		// 🆕 新增：设置分类树
		SET_CATEGORY_TREE(state, categoryTree) {
			state.categoryTree = categoryTree;
		},

		SET_RECORDS(state, records) {
			state.records = records;
		},

		ADD_RECORD(state, record) {
			state.records.unshift(record);
		},

		UPDATE_RECORD(state, updatedRecord) {
			const index = state.records.findIndex(item => item.id === updatedRecord.id);
			if (index !== -1) {
				state.records.splice(index, 1, updatedRecord);
			}
		},

		DELETE_RECORD(state, id) {
			const index = state.records.findIndex(item => item.id === id);
			if (index !== -1) {
				state.records.splice(index, 1);
			}
		},

		SET_LOADING(state, {
			type,
			status
		}) {
			if (state.loading.hasOwnProperty(type)) {
				state.loading[type] = status;
			}
		},

		CLEAR_USER_DATA(state) {
			state.accessToken = '';
			state.refreshToken = '';
			state.userInfo = null;
			state.records = [];
			state.categories = [];
			storage.clearTokens();
		}
	},

	actions: {
		async login({
			commit,
			dispatch
		}, loginData) {
			commit('SET_LOADING', {
				type: 'user',
				status: true
			});

			try {
				const response = await authApi.login(loginData);
				console.log('完整的response结构:', response);
				console.log('response.data结构:', response.data);
				console.log('response.data.code:', response.data.code);
				if (response.data.code === 200) {
					const tokenData = response.data.data; // 真正的token数据在这个data属性里
					console.log('真正的token数据:', tokenData);

					commit('SET_ACCESS_TOKEN', tokenData);
					commit('SET_REFRESH_TOKEN', tokenData.refreshToken);

					try {
						await dispatch('getUserInfo');
					} catch (userInfoError) {
						console.warn('⚠️ 获取用户信息失败，但不影响登录:', userInfoError);
						// 可以设置默认用户信息或继续流程
						const defaultUserInfo = {
							username: loginData.username
						};
						commit('SET_USER_INFO', defaultUserInfo);
					}

					uni.showToast({
						title: '登录成功',
						icon: 'success'
					});

					return Promise.resolve(response.data);
				} else {
					return Promise.reject(new Error(response.data.message || '登录失败'));
				}
			} catch (error) {
				console.error('Login error:', error);
				uni.showToast({
					title: error.message || '登录失败',
					icon: 'none'
				});
				return Promise.reject(error);
			} finally {
				commit('SET_LOADING', {
					type: 'user',
					status: false
				});
			}
		},

		async register({
			commit,
			dispatch
		}, registerData) {
			commit('SET_LOADING', {
				type: 'user',
				status: true
			});

			try {
				const response = await authApi.register(registerData);

				if (response.data.code === 200) {
					const tokenData = response.data.data;

					commit('SET_ACCESS_TOKEN', tokenData);
					commit('SET_REFRESH_TOKEN', tokenData.refreshToken);

					try {
						await dispatch('getUserInfo');
					} catch (userInfoError) {
						console.warn('⚠️ 获取用户信息失败，但不影响登录:', userInfoError);
						// 可以设置默认用户信息或继续流程
						const defaultUserInfo = {
							username: loginData.username
						};
						commit('SET_USER_INFO', defaultUserInfo);
					}

					uni.showToast({
						title: '注册成功',
						icon: 'success'
					});

					return Promise.resolve(response.data);
				} else {
					return Promise.reject(new Error(response.data.message || '注册失败'));
				}
			} catch (error) {
				console.error('Register error:', error);
				uni.showToast({
					title: error.message || '注册失败',
					icon: 'none'
				});
				return Promise.reject(error);
			} finally {
				commit('SET_LOADING', {
					type: 'user',
					status: false
				});
			}
		},

		async getUserInfo({
			commit
		}) {
			try {
				const response = await userApi.getUserInfo();
				console.log('👤 getUserInfo完整响', response);
				console.log('👤 response.data结构:', response.data);

				if (response.data.code === 200) {
					const userData = response.data.data;
					console.log('👤 真正的用户数据:', userData);
					commit('SET_USER_INFO', userData);
					return Promise.resolve(response.data);
				} else {
					return Promise.reject(new Error(response.data.message || '获取用户信息失败'));
				}
			} catch (error) {
				console.error('Get user info error:', error);
				return Promise.reject(error);
			}
		},

		async refreshToken({
			commit,
			state
		}) {
			try {
				const response = await authApi.refreshToken({
					refreshToken: state.refreshToken
				});

				if (response.data.code === 200) {
					const tokenData = response.data.data;
					commit('SET_ACCESS_TOKEN', tokenData.accessToken);
					if (tokenData.refreshToken) {
						commit('SET_REFRESH_TOKEN', tokenData.refreshToken);
					}
					return Promise.resolve(tokenData);
				} else {
					return Promise.reject(new Error(response.data.message || '刷新令牌失败'));
				}
			} catch (error) {
				console.error('Refresh token error:', error);
				commit('CLEAR_USER_DATA');
				return Promise.reject(error);
			}
		},

		async logout({
			commit
		}) {
			try {
				await authApi.logout();
			} catch (error) {
				console.error('Logout API error:', error);
			} finally {
				commit('CLEAR_USER_DATA');

				uni.showToast({
					title: '已退出登录',
					icon: 'success'
				});

				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}, 1500);
			}
		},

		async loadCategories({
			commit,
			state
		}, type = null) {
			commit('SET_LOADING', {
				type: 'categories',
				status: true
			});

			try {
				const response = await categoryApi.getCategoryList();
				console.log('🔍 完整响应结构:', response);

				if (response.statusCode === 200) {
					const categories = response.data.data;
					console.log('📊 获取到的分类数据:', categories);
					const filteredCategories = type !== null ?
						categories.filter(item => item.type === type) :
						categories;

					commit('SET_CATEGORIES', filteredCategories);
					return Promise.resolve(response.data);
				} else {
					return Promise.reject(new Error(response.data.message || '获取分类失败'));
				}
			} catch (error) {
				console.error('Load categories error:', error);
				uni.showToast({
					title: '加载分类失败',
					icon: 'none'
				});
				return Promise.reject(error);
			} finally {
				commit('SET_LOADING', {
					type: 'categories',
					status: false
				});
			}
		},

		async loadRecords({
			commit,
			state
		}, params = {}) {
			commit('SET_LOADING', {
				type: 'records',
				status: true
			});

			try {
				// 使用真实接口调用
				const response = await recordApi.getRecords(params);

				if (response.statusCode === 200) {
					const records = response.data.data;

					commit('SET_RECORDS', records);

					return Promise.resolve(response.data);
				} else {
					// 接口返回错误码
					const errorMessage = response.data.message || '获取记录列表失败';
					uni.showToast({
						title: errorMessage,
						icon: 'none'
					});
					return Promise.reject(new Error(errorMessage));
				}
			} catch (error) {
				console.error('Load records error:', error);
				// 更详细的错误处理
				let errorMessage = '加载记录失败';
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 3000
				});
				return Promise.reject(error);
			} finally {
				commit('SET_LOADING', {
					type: 'records',
					status: false
				});
			}
		},

		// 🆕 新增：加载分类树形结构
		async loadCategoryTree({
			commit
		}) {
			commit('SET_LOADING', {
				type: 'categories',
				status: true
			});

			try {
				const response = await categoryApi.getCategoryTree();
				console.log('🌳 分类树响应结构:', response);

				if (response.statusCode === 200) {
					const categoryTree = response.data;
					console.log('📊 获取到的分类树数据:', categoryTree);

					// 🆕 将分类树存储到新的状态中
					commit('SET_CATEGORY_TREE', categoryTree);
					return Promise.resolve(response.data);
				} else {
					return Promise.reject(new Error(response.message || '获取分类树失败'));
				}
			} catch (error) {
				console.error('Load category tree error:', error);
				// 🆕 使用默认的分类树数据作为fallback
				const defaultCategoryTree = getDefaultCategoryTree();
				commit('SET_CATEGORY_TREE', defaultCategoryTree);

				uni.showToast({
					title: '加载分类树失败，使用默认数据',
					icon: 'none'
				});
				return Promise.reject(error);
			} finally {
				commit('SET_LOADING', {
					type: 'categories',
					status: false
				});
			}
		},

		async addRecord({
			commit
		}, recordData) {
			try {
				const response = await recordApi.addRecord(recordData);

				if (response.statusCode === 200) {
					commit('ADD_RECORD', response.data.data);
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
					return Promise.resolve(response);
				} else {
					return Promise.reject(new Error(response.data.message || '添加记录失败'));
				}
			} catch (error) {
				console.error('Add record error:', error);
				uni.showToast({
					title: '添加记录失败',
					icon: 'none'
				});
				return Promise.reject(error);
			}
		},

		async updateRecord({
			commit
		}, {
			id,
			recordData
		}) {
			try {
				const response = await recordApi.updateRecord(id, recordData);

				if (response.code === 200) {
					commit('UPDATE_RECORD', response.data);
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					});
					return Promise.resolve(response);
				} else {
					return Promise.reject(new Error(response.message || '更新记录失败'));
				}
			} catch (error) {
				console.error('Update record error:', error);
				uni.showToast({
					title: '更新记录失败',
					icon: 'none'
				});
				return Promise.reject(error);
			}
		},

		async deleteRecord({
			commit
		}, id) {
			try {
				const response = await recordApi.deleteRecord(id);

				if (response.code === 200) {
					commit('DELETE_RECORD', id);
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					return Promise.resolve(response);
				} else {
					return Promise.reject(new Error(response.message || '删除记录失败'));
				}
			} catch (error) {
				console.error('Delete record error:', error);
				uni.showToast({
					title: '删除记录失败',
					icon: 'none'
				});
				return Promise.reject(error);
			}
		}
	},

	getters: {
		isLoggedIn: state => !!state.accessToken,
		userInfo: state => state.userInfo,
		accessToken: state => state.accessToken,
		refreshToken: state => state.refreshToken,
		isLoading: state => type => state.loading[type] || false,

		incomeCategories: state => state.categories.filter(item => item.type === 1),
		expenseCategories: state => {
			return state.categories.filter(item => item.type === 0) || [];
		},

		//分类树相关的 getters
		categoryTree: state => state.categoryTree || [],

		// 从分类树中提取不同类型的分类
		treeExpenseCategories: state => {
			const expense = state.categoryTree.find(cat => cat.name === '支出' || cat.type === 0);
			return expense ? expense.children || [] : [];
		},

		todayRecords: state => {
			const today = new Date().toISOString().split('T')[0];
			return state.records.filter(record => record.recordDate === today);
		},

		monthlyIncome: state => {
			const currentMonth = new Date().toISOString().substring(0, 7);
			return state.records
				.filter(record => record.type === 1 && record.recordDate.startsWith(currentMonth))
				.reduce((sum, record) => sum + parseFloat(record.amount), 0);
		},

		monthlyExpense: state => {
			const currentMonth = new Date().toISOString().substring(0, 7);
			return state.records
				.filter(record => record.type === 0 && record.recordDate.startsWith(currentMonth))
				.reduce((sum, record) => sum + parseFloat(record.amount), 0);
		},

		monthlyBalance: (state, getters) => {
			return getters.monthlyIncome - getters.monthlyExpense;
		},

		categoryStatistics: state => {
			const stats = {};
			state.records.forEach(record => {
				if (!stats[record.categoryId]) {
					stats[record.categoryId] = {
						categoryId: record.categoryId,
						categoryName: record.categoryName,
						amount: 0,
						count: 0
					};
				}
				stats[record.categoryId].amount += parseFloat(record.amount);
				stats[record.categoryId].count += 1;
			});
			return Object.values(stats);
		}
	}
});

export default store;